package com.farsight.leo.fssmartlock.activities;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.farsight.leo.fssmartlock.Constants;
import com.farsight.leo.fssmartlock.R;
import com.farsight.leo.fssmartlock.bases.BaseActivity;
import com.farsight.leo.fssmartlock.bases.BaseApplication;
import com.farsight.leo.fssmartlock.net.OkHttpHelper;
import com.farsight.leo.fssmartlock.net.bases.BaseOkHttpCallback;
import com.farsight.leo.fssmartlock.net.bean.UserData;
import com.farsight.leo.fssmartlock.utils.ToastUtils;

import androidx.appcompat.widget.AppCompatEditText;

public class LoginActivity extends BaseActivity {

    private AppCompatEditText mEdtUserName;
    private AppCompatEditText mEdtPw;

    public static void start(Context context) {
        Intent starter = new Intent(context, LoginActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int set_layout_id() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        mEdtUserName = findViewById(R.id.activity_login_edt_user_name);
        mEdtPw = findViewById(R.id.activity_login_edt_pw);

    }

    @Override
    protected void initListeners() {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        UserData data = intent.getParcelableExtra(Constants.KEY_USER_DATA);
        int intendCode = intent.getIntExtra(Constants.KEY_INTENT_SOURCE, -1);
        if (data != null && intendCode == Constants.INTENT_REGISTER_OK) {
            mEdtUserName.setText(data.getUser_name());
            mEdtPw.setText(data.getUser_password());
            login(data);
        }
    }

    private void login(UserData userData) {
        OkHttpHelper.getInstance().userLogin(userData, new BaseOkHttpCallback<UserData>() {
            @Override
            public void onError(final String err) {
                ToastUtils.showToast(err);
            }

            @Override
            public void onSuccess(UserData result) {
                BaseApplication.setUserData(result);
                PostLoginActivity.start(LoginActivity.this);
                finish();
            }
        });
//        OkHttpHelper.getInstance().genericHttpRequest(); //测试用

    }

    public void login(View view) {
        String name = mEdtUserName.getText().toString().trim();
        String pw = mEdtPw.getText().toString().trim();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pw)) {
            return;
        }
        UserData userData = new UserData();
        userData.setUser_name(name);
        userData.setUser_password(pw);
        login(userData);
    }

    public void register(View view) {
        RegisterActivity.start(this);
    }
}
